package com.lyl.security.module.security.service;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.jwt.JWTUtil;
import com.lyl.security.module.security.model.dto.UserDTO;
import com.lyl.security.module.security.model.pojo.LoginDetails;
import com.lyl.security.module.security.model.properties.SecurityProperties;
import com.lyl.security.module.security.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author Mr.Luo
 * @date 2022-09-05 10:41
 * @desc
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final SecurityProperties securityProperties;

    @Override
    public String login(UserDTO dto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate.isAuthenticated()) {
            //登录成功
            //1. 生成token
            //2. 将登录用户的信息存入redis中
            LoginDetails loginDetails = (LoginDetails) authenticate.getPrincipal();
            String token = Base64Encoder.encode(JWTUtil.createToken(MapUtil.builder("userId", (Object) loginDetails.getUser().getId()).build(), securityProperties.getToken().getPrivateKey().getBytes(StandardCharsets.UTF_8)));
            log.info("用户[{}]登录成功，token: {}", dto.getUsername(), token);
            //3. 返回登录成功和token
            return token;
        }
        return "登录失败";
    }
}
